<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Easy Login
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

define('MIN_PASSWD_LENGTH', 8);

class retrievePassword extends FrontControllerCore
{
	public function run()
	{
		$this->init();
//		$this->preProcess();
//		$this->displayHeader();
		$this->process();
//		$this->displayContent();
//		$this->displayFooter();
	}
	
	public function process()
	{

		if (Tools::isSubmit('SubmitPassword'))
		{
			global $cookie, $link;
			$checkPassword = false;
			
			if (!($email = Tools::getValue('email')) OR !Validate::isEmail($email))
				$this->errors[] = Tools::displayError('Invalid e-mail address');
			else
			{
				$customer = new Customer();
				$customer->getByemail($email);
				if (!Validate::isLoadedObject($customer))
					$this->errors[] = Tools::displayError('There is no account registered to this e-mail address.');
				else
				{
					if ((strtotime($customer->last_passwd_gen.'+'.(int)($min_time = Configuration::get('PS_PASSWD_TIME_FRONT')).' minutes') - time()) > 0)
						$this->errors[] = Tools::displayError('You can regenerate your password only every').' '.(int)($min_time).' '.Tools::displayError('minute(s)');
					else
					{	
						if (Mail::Send((int)($cookie->id_lang), 'password_query', Mail::l('Password query confirmation'), 
						array('{email}' => $customer->email, 
							  '{lastname}' => $customer->lastname, 
							  '{firstname}' => $customer->firstname,
							  '{url}' => $link->getPageLink('password.php', true).'?token='.$customer->secure_key.'&id_customer='.(int)$customer->id),
						$customer->email, 
						$customer->firstname.' '.$customer->lastname))
							$checkPassword = true;
						else
							$this->errors[] = Tools::displayError('Error occurred when sending the e-mail.');
					}
				}
			}
			
			if (Tools::isSubmit('ajax'))
			{
					$return = array(
						'hasError' => !empty($this->errors),
						'errors' => $this->errors,
						'email' => Tools::getValue('email'),
						'token' => Tools::getToken(false)
					);
						
				die(Tools::jsonEncode($return));
			}
		}
	}
}